import { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";

import { InboxOutlined } from "@ant-design/icons";
import { message, Modal, Upload, UploadFile, UploadProps } from "antd";

import {
  EyeOutlined,
  DownloadOutlined,
  SortAscendingOutlined,
} from "@ant-design/icons";

import { forwardRef, useImperativeHandle } from "react";
import history from "@/utils/history";

const { Dragger } = Upload;

type props = {
  fileData: any[];
  myUrl: string;
  ref: any;
  fromData: any;
};

function ZupFileDrag({ fileData, myUrl, fromData }: props, ref: any) {
  useEffect(() => {
    const arr: UploadFile[] = fileData.map((v) => ({
      uid: v.id,
      name: v.fileName,
      status: "done",
      percent: 100,
      response: {
        data: v,
      },
    }));
    setFileList(arr);
  }, [fileData]);

  const [modal, contextHolder] = Modal.useModal();

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const FileProps: UploadProps = {
    name: "file",
    multiple: true,
    action: myUrl,
    headers: {
      token:
        "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlkIjoxLCJpc0FkbWluIjoxLCJ1c2VyTmFtZSI6ImFkbWluIiwiZXhwIjoxNjg5OTI5MTMyLCJyb2xlS2V5cyI6WyJzeXNfYWRtaW4iXSwiaWF0IjoxNjg5ODQyNzMyLCJqdGkiOiIyZGNjNTk4Zi1iMzVmLTQzNjctOGU3YS1kZDQwNGE4N2E0YTAifQ.t3yZf7XersF1rV_ODiTGDO9zYn7_TwjBk-q1_SUdvHc",
    },
    // 支持上传文件夹
    directory: true,
    data: fromData,
    fileList,
    //不要前面的图标
    // iconRender: () => false,
    // 文件上传之前
    beforeUpload(file, fileList) {
      // console.log("文件上传之前-用于校验", file);

      if (file.name.includes("4dage")) {
        // console.log("校验不通过，不上传");
        message.error(`${file.name}不符合上传需求`);
        return Upload.LIST_IGNORE;
      }
    },
    onChange(info) {
      setFileList([...info.fileList]);

      const { status } = info.file;
      if (status !== "uploading") {
        // 检查请求状态
        const response = info.file.response || {};

        if (response.code !== 0) {
          setFileList(info.fileList.filter((v) => v.uid !== info.file.uid));
        }
        if (response.code === 5001 || response.code === 5002) {
          message.warning("登录失效!");
          history.push("/login");
          return false;
        }

        // console.log(info.file, info.fileList);
      }
      if (status === "done") {
        // message.success(`${info.file.name} 上传成功.`);
      } else if (status === "error") {
        message.error(`${info.file.name} 上传失败.`);
        // 去掉列表中的失败状态文件
        setFileList(info.fileList.filter((v) => v.uid !== info.file.uid));
      }
    },
    onDrop(e) {
      // console.log("拖动文件到上传区域", e.dataTransfer.files);
    },
    // 点击删除
    async onRemove(info) {
      const promiseFu = new Promise((resolve: (value: boolean) => void) => {
        modal.confirm({
          title: "操作确认",
          content: "是否确认删除？",
          okText: "确定",
          cancelText: "取消",
          onOk() {
            console.log('-----',info);
            
            resolve(true);
          },
          onCancel() {
            resolve(false);
          },
        });
      });
      return await promiseFu;
    },
  };

  const lookFlag = useCallback((name: string) => {
    const temp = name.split(".")[1];
    const arr = ["png", "jpeg", "jpg", "gif", "mp3", "wav", "mp4", "4dage"];

    if (arr.includes(temp)) return true;
    else return false;
  }, []);

  // 点击查看
  const lookFileFu = useCallback((data: any) => {
    console.log("点击查看", data);

    let myType = "";

    const temp = data.fileName.split(".")[1];
    if (["png", "jpeg", "jpg", "gif"].includes(temp)) {
      console.log("类型是图片");
      //   store.dispatch({
      //     type: "layout/lookBigImg",
      //     payload: { url: baseURL + v.response.data.filePath, show: true },
      //   })
    } else if (["mp3", "wav"].includes(temp)) {
      console.log("类型是音频");
      myType = "audio";
    } else if (["mp4"].includes(temp)) {
      console.log("类型是视频");
      myType = "video";
    } else if (["4dage"].includes(temp)) {
      console.log("类型是视频");
      myType = "model";
      console.log("---", myType);

      // store.dispatch({
      //   type: "layout/lookDom",
      //   payload: { src: fileUrl.path, type: myType },
      // })
    }
  }, []);

  // 有关排序的操作：

  const showInpRef = useRef<HTMLInputElement>(null);
  const [sortClickNum, setSortClickNum] = useState(-1);

  //  点击排序
  const sortShowFu = useCallback((ind: number) => {
    setSortClickNum(ind);
    setSortValue(ind + 1 + "");
    setTimeout(() => {
      if (showInpRef.current) showInpRef.current.focus();
    }, 100);
  }, []);

  const [sortValue, setSortValue] = useState("");
  const sortValueChange = useCallback(
    (val: string) => {
      if (Number(val) > fileList.filter((v) => v.percent === 100).length)
        val = fileList.filter((v) => v.percent === 100).length + "";
      setSortValue(val.replace(/^(0+)|[^\d]+/g, ""));
    },
    [fileList]
  );

  // 点击序号的 √
  const sortOkFu = useCallback(
    (oldInd: number) => {
      if (!sortValue) return message.warning("请输入序号值!");

      const newInd = Number(sortValue) - 1;

      if (oldInd === newInd) return message.warning("不能和之前的序号一样!");

      const newArr = [...fileList];
      newArr[oldInd] = fileList[newInd];
      newArr[newInd] = fileList[oldInd];
      setFileList(newArr);

      message.success("修改序号成功!");
      setSortClickNum(-1);
    },
    [fileList, setFileList, sortValue]
  );

  const inputKeyFu = useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>, ind: number) => {
      if (e.key === "Enter") {
        sortOkFu(ind);
        e.preventDefault();
      }
    },
    [sortOkFu]
  );

  // 给父组件点击确定 调用
  const clickOkFu = useCallback(() => {
    console.log("-----", fileList);

    // 拿到 后端返回 的 id列表
    const ids = [] as Number[];
    fileList.forEach((v) => {
      // 看下是否全部传输完成
      if (v.percent !== 100) return message.warning("有文件未上传完成.");

      ids.push(v.response.data.id);
    });
    // console.log("点击确定", ids.join(","));

    return ids.join(",");
  }, [fileList]);

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    clickOkFu,
  }));

  return (
    <div className={styles.ZupFileDrag}>
      <Dragger {...FileProps}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined rev={undefined} />
        </p>
        <p className="ant-upload-text">点击上传整个文件夹</p>
        <p className="ant-upload-hint">或者拖动多个文件/文件夹至此处上传</p>
        <p className="ant-upload-hint" hidden={fileList.length <= 1}>
          点击
          <SortAscendingOutlined rev={undefined} />
          ，输入 1 - {fileList.filter((v) => v.percent === 100).length}{" "}
          的整数，按 Enter 键来交换2个文件的位置
        </p>
      </Dragger>
      {/* 自定义 预览 下载 删除 */}
      <div className="myIncoBox">
        {fileList.map(
          (v, i) =>
            v.response &&
            v.response.data && (
              <div className="myIncoRow" key={v.uid}>
                {lookFlag(v.response.data.fileName) ? (
                  <>
                    {/* // 1.预览（name里面有常用的，浏览器能识别的 图片 音频 视频 模型） */}
                    <div title="预览文件">
                      <EyeOutlined
                        rev={undefined}
                        onClick={() => lookFileFu(v.response.data)}
                      />
                    </div>
                  </>
                ) : null}
                {/* // 2.下载 */}
                <div title="下载文件">
                  <a
                    href="baseURL+v.response.data.filePath"
                    target="blank"
                    download
                  >
                    <DownloadOutlined rev={undefined} />
                  </a>
                </div>
                {/* 3.前面的序号 */}
                <div className="mySortQ" hidden={fileList.length <= 1}>
                  {i + 1}.
                </div>

                {/* 后面的排序标签 */}
                <div
                  className="sotrIcon"
                  title="文件排序"
                  hidden={fileList.length <= 1}
                >
                  <SortAscendingOutlined
                    rev={undefined}
                    onClick={() => sortShowFu(i)}
                  />
                  &emsp;
                  {sortClickNum === i ? (
                    <input
                      onBlur={() => setSortClickNum(-1)}
                      onKeyDown={(e) => inputKeyFu(e, i)}
                      ref={showInpRef}
                      maxLength={5}
                      type="text"
                      value={sortValue}
                      onChange={(e) => sortValueChange(e.target.value)}
                    />
                  ) : null}
                </div>
              </div>
            )
        )}
      </div>
      {contextHolder}
    </div>
  );
}

// const MemoZupFileDrag = React.memo(ZupFileDrag);

export default forwardRef(ZupFileDrag);
